package com.shopping_back.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.mapper.NoticeMapper;
import com.shopping_back.pojo.dto.NoticeCreateDTO;
import com.shopping_back.pojo.dto.NoticeUpdateDTO;
import com.shopping_back.pojo.dto.PageDTO;
import com.shopping_back.pojo.entity.Notice;
import com.shopping_back.service.INoticeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;

@Service
@RequiredArgsConstructor
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice>
        implements INoticeService {

    @Override
    public PageDTO<Notice> listPage(Integer pageNum, Integer pageSize,
                                    String title, Integer type) {

        LambdaQueryWrapper<Notice> qw = new LambdaQueryWrapper<>();
        qw.eq(Notice::getIsDeleted, 0);
        if (StringUtils.hasText(title)) {
            qw.like(Notice::getTitle, title.trim());
        }
        if (type != null) {
            qw.eq(Notice::getType, type);
        }
        qw.orderByDesc(Notice::getCreateTime);

        Page<Notice> page = this.page(new Page<>(pageNum, pageSize), qw);

        PageDTO<Notice> dto = new PageDTO<>();
        dto.setList(page.getRecords());
        dto.setTotal(page.getTotal());
        dto.setCurrentPage((int) page.getCurrent());
        dto.setPageSize((int) page.getSize());
        return dto;
    }

    @Override
    @Transactional
    public void create(NoticeCreateDTO dto) {
        Notice n = new Notice();
        n.setTitle(dto.getTitle());
        n.setContent(dto.getContent());
        n.setType(dto.getType());
        this.save(n);
    }

    @Override
    @Transactional
    public void updateBasic(NoticeUpdateDTO dto) {
        Notice n = this.getById(dto.getId());
        if (n == null) {
            throw new RuntimeException("通知不存在");
        }
        n.setTitle(dto.getTitle());
        n.setContent(dto.getContent());
        n.setType(dto.getType());
        this.updateById(n);
    }

    @Override
    public List<Notice> listAll(Integer type) {
        LambdaQueryWrapper<Notice> qw = Wrappers.<Notice>lambdaQuery()
                .eq(Notice::getIsDeleted, 0)            // 仅未删除
                .orderByDesc(Notice::getCreateTime);    // 最新在前
        if (type != null) qw.eq(Notice::getType, type); // 可选类型过滤
        return this.list(qw);
    }
}
